package com.util.concurrent.locks;

import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * {@code Condition}是1.5加的,用替代{@code Object}的{@link #wait()}和{@link #notify()}来一起解决线程同步的问题
 * @author Ackles
 */
public class ConditionDemo {
	
	private static int holder = 4;
	private static Random rand = new Random();
	private static Lock lock = new ReentrantLock();
	private static Condition condition = lock.newCondition();

	public static void main(String[] args) {
		ConditionDemo demo = new ConditionDemo();
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						lock.lock();
						demo.produce();
					} finally {
						lock.unlock();
					}
				}
			}
		}).start();
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					demo.consume();
				}
			}
		}).start();
	}
	
	void produce() {
		int nextInt = rand.nextInt(holder) + 1;
		System.out.println(String.format("produce holder=%d, next=%d", holder, nextInt));
		holder += nextInt;
		System.out.println(String.format("produce holder=%d, next=%d, ok.", holder, nextInt));
	}
	
	void consume() {
		System.out.println(String.format("consume holder=%d", holder));
		if (holder < 5) {
			return;
		}
		int nextInt = rand.nextInt(holder);
		System.out.println(String.format("consume holder=%d, next=%d", holder, nextInt));
		holder -= nextInt;
		System.out.println(String.format("consume holder=%d, next=%d, ok.", holder, nextInt));
	}
}
